#include "gqueue.h"
#include <string.h>

/** Initialize the queue
*/
GQueue * newGQueue(int n_ele, int size_ele) 
{
	GQueue *q = (GQueue *) malloc(sizeof(GQueue));
	
	q->ptr = malloc(n_ele * size_ele);
	q->in = 0;
	q->out = 0;
	q->cnt = 0;
	q->size = n_ele;
	q->ele_size = size_ele;
	
	return q;
}

/** Delete the queue
*/
void deleteGQueue(GQueue *q) 
{
	free(q->ptr);
	free(q);
}

/** Put ele in the queue pointed to by 'q'
* Returns false if operation failed (the queue is full)
*/
Bool putGQueue(GQueue *q, void *ele)
{
	if( isFullGQueue(q) )
		return false;
	
	//copies ele with ele_size to memory pointed by q->ptr plus p->in
	memcpy( q->ptr + q->in, ele, q->ele_size);

	if(q->in == (q->size*q->ele_size))
		q->in = 0;
	
	q->in += q->ele_size;
	q->cnt++;

	return true;
}

/** Get next element from queue
*  Returns -1 (an int) if there are no elements in the queue
*/
void * getGQueue(GQueue *q)
{
	if( isEmptyGQueue(q) )
		return NULL;
		
	void * ele = q->ptr + q->out;
	
	if(q->out == (q->size*q->ele_size))
		q->out = 0;
	
	q->out += q->ele_size;
	
	q->cnt--;

	return ele;

}

/** Returns true if the queue is empty
*/
Bool isEmptyGQueue(GQueue *q)
{
	return (q->cnt == 0);
}

/** Returns true if the queue is full
*/
Bool isFullGQueue(GQueue *q)
{
	return (q->cnt == q->size);
}
